package com.kgc.scd;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.kgc.scd.bean.Product;
import com.kgc.scd.bean.ProductXZY;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import com.alibaba.fastjson.JSON;

import com.kgc.scd.contant.CommonConstant;
import com.kgc.scd.service.ProductService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.io.IOException;
import java.util.List;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableSwagger2
@EnableSwaggerBootstrapUI
@MapperScan("com.kgc.scd.mapper")
public class BlmallServerXzy8101Application implements ApplicationRunner{

    @Autowired
    private ProductService productService;

    public static void main(String[] args) {
        SpringApplication.run(BlmallServerXzy8101Application.class, args);
    }



     @Override
     public void run(ApplicationArguments applicationArguments) throws Exception {
         // 项目一启动从mysql中取出所有的商品存入es中
         // 清空es中blmall索引的数据
         RestHighLevelClient esClient = new RestHighLevelClient(
                 RestClient.builder(new HttpHost("localhost",9200,"http"))
         );
         // 如果存在删除索引
         ifHaveIndex(esClient,CommonConstant.BLMALL_PRODUCT_ES_INDEX);
         CreateIndexRequest request = new CreateIndexRequest(CommonConstant.BLMALL_PRODUCT_ES_INDEX);
         XContentBuilder builder = XContentFactory.jsonBuilder();
         // 创建索引
         builder.startObject();
         {
             builder.startObject("properties");
             {
                 builder.startObject("proId");
                 {
                     builder.field("type","keyword");
                 }
                 builder.endObject();
                 // 商品名
                 builder.startObject("proName");
                 {
                     builder.field("type","text")
                             .field("analyzer","ik_max_word")
                             .field("search_analyzer","ik_smart");
                 }
                 builder.endObject();
                 // 商品价格
                 builder.startObject("proPrice");
                 {
                     builder.field("type","keyword");
                 }
                 builder.endObject();

                 // 商品图片
                 builder.startObject("proPic");
                 {
                     builder.field("type","keyword")
                     .field("index",false);
                 }
                 builder.endObject();

                 // 商品种类id
                 builder.startObject("proCategoryid");
                 {
                     builder.field("type","keyword")
                             .field("index",false);
                 }
                 builder.endObject();

                 // 商品种类名字
                 builder.startObject("categoryName");
                 {
                     builder.field("type","keyword")
                             .field("index",false);
                 }
                 builder.endObject();

             }
             builder.endObject();
         }
         builder.endObject();

         request.mapping(builder);
         CreateIndexResponse response = esClient.indices().create(request, RequestOptions.DEFAULT);
         //System.out.println(response.isAcknowledged());
         // 创建商品索引成功 获取所有商品
             List<ProductXZY> products = productService.getAllProduct();
             // 放入es中
             BulkRequest bulkRequest = new BulkRequest();
             for(int i= 0;i<products.size();i++){
                 bulkRequest.add(new IndexRequest(CommonConstant.BLMALL_PRODUCT_ES_INDEX)
                                     .source(JSON.toJSONString(products.get(i)), XContentType.JSON));
             }
         BulkResponse bulk = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
         esClient.close();


         //if(createIndex(esClient, CommonConstant.BLMALL_PRODUCT_ES_INDEX)){
         //    // 创建商品索引成功 获取所有商品
         //    List<Product> products = productService.getAllProduct();
         //    // 放入es中
         //    BulkRequest bulkRequest = new BulkRequest();
         //    for(int i= 0;i<products.size();i++){
         //        bulkRequest.add(new IndexRequest(CommonConstant.BLMALL_PRODUCT_ES_INDEX)
         //                            .source(JSON.toJSONString(products.get(i)), XContentType.JSON));
         //    }
         //    BulkResponse bulk = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
         //    // 关闭es客户端
         //    esClient.close();
         //}


     }

     // 创建ES索引
     public static boolean ifHaveIndex(RestHighLevelClient client, String index) throws IOException {
         GetIndexRequest existsRequest = new GetIndexRequest(index);
         boolean exists = client.indices().exists(existsRequest,RequestOptions.DEFAULT);
         try {
             if(exists){
                 // 如果存在，删除索引
                 DeleteIndexRequest deleteRequest = new DeleteIndexRequest(index);
                 AcknowledgedResponse response = client.indices().delete(deleteRequest, RequestOptions.DEFAULT);
                 return response.isAcknowledged();
             }
             return false;
         } catch (IOException e) {
             e.printStackTrace();
             return false;
         }
     }

}
